import React, { Component } from 'react'
import {CarProductInter} from '../../types/product.d'
import {connect} from 'react-redux'
interface Iprops{
    item:CarProductInter,
    changeNum:(num:number,id:number) => void,
    open:(id:number) => void,
    changeCheked:(id:number,checked:boolean) => void
}

class CarProduct extends Component<Iprops>{
    render() {
        let {title,num,checked,price} = this.props.item
        return (
            <div>
                <input type="checkbox" checked={checked} onChange={this.change}/>
                <div>
                    <h4>{title}</h4>
                    <span>{price}</span>
                </div>
                <div>
                    <span onClick={() => {
                        this.changeNum(true) 
                    }}>-</span>
                    <span>{num}</span>
                    <span onClick={() => {
                        this.changeNum(false)
                    }}>+</span>
                </div>
            </div>
        )
    }

    //改变选中状态
    change = (e:any) => {
        let {id} = this.props.item;
        this.props.changeCheked(id,e.target.checked)
    }

    changeNum = (flag:boolean) => {
        let {num,id} = this.props.item;
        //true 加法  false:减法
        if(flag){
            //如果为1的时候，出现弹窗
            if(num <= 1){
                //出现弹窗
                console.log("出现弹窗")
                this.props.open(id)
            }else{
                num = num - 1;
            }
        }else{
            num = num + 1;
        }

        this.props.changeNum(num,id)
    }
}

let stateMapToProps = () => {
    return {}
}

let dispatchMapToProps = (dispatch:any) => {
    return {
        changeNum(num:number,id:number){
            dispatch({type:'CHANGE_NUM',num,id})
        },
        changeCheked(id:number,checked:boolean){
            dispatch({type:'CHANGE_CHECKED',id,checked})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(CarProduct)